<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\common\components\IpLocation;
use app\index\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use think\Request;

class Tool extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('index',[
            'crumb' => [
                'home' => '/',
                '工具列表' => request()->url()
            ]
        ]);
    }

    /**
     * IP工具页面
     */
    public function ipTool(){
        return view('ip-tool',[
            'ipLocation' => (new IpLocation(request()->ip()))->getInfo(),
            'crumb' => [
                'home' => '/',
                'IP工具' => request()->url()
            ]
        ]);
    }


    /**
     * ip查询接口
     */
    public function ipLocation(){

        try{
            //回调
            $callback = config('route.var_jsonp_handler');
            //验证数据
            $data = request()->only(['ip', $callback]);

            validate([
                'ip' => 'require|ip',
                'callback' => 'alphaDash'
            ],[
                'ip.require' => 'ip不能为空',
                'ip.ip' => 'ip格式错误',
                'callback.alphaDash' => '回调应为字母和数字，下划线_及破折号-'
            ])->check($data);


            //ip信息
            //$info = (new IpLocation($data['ip']))->limit()->getInfo();
            $info = (new IpLocation($data['ip']))->getInfo();

            $ret = [
                'code' => 0,
                'data' => $info
            ];

            //返回数据
            if (empty($data[$callback]))
                return json($ret);
            else
                //jsonp
                return jsonp($ret);

        } catch (ValidateException $e) {
            $ret = [
                'code' => 1,
                'msg' => $e->getMessage()
            ];

            //返回数据
            if (empty($data['callback']))
                return json($ret);
            else
                //jsonp
                return $data['callback'] . '('. jsonStr($ret) .')';
        } catch (\Exception $e){

            //Log::error($e->getMessage());
            $ret = [
                'code' => 1,
                'msg' => $e->getMessage()
            ];

            //返回数据
            if (empty($data['callback']))
                return json($ret);
            else
                //jsonp
                return $data['callback'] . '('. jsonStr($ret) .')';
        }



    }
}
